package GDoc::Job::Fetch::US::Exec::CIA::FOIAReports;

use Moose;

use WWW::Mechanize;
use GDoc::Job;
use File::Temp;


extends 'GDoc::Job::Fetch';

sub setup {
    my $self = shift;
    $self->_baseurl( 'http://www.foia.cia.gov/annual_report.asp' );
    $self->_basedir( 'http://www.foia.cia.gov/' );
}

sub run { 
    my $self = shift;
   
    if ( $self->data->{link} ) { 
        $self->_fetch_pdf;
    } else { 
        $self->logger->info( "fetching base " . $self->_baseurl );
        my $mech = $self->_mech;
        $mech->get( $self->_baseurl );
        my @links = $mech->find_all_links( url_regex => qr{annual_report_\d{4}\.pdf$} );

        foreach my $link( @links ) { 
            my $year = $link->text;

            my $job = GDoc::Job->new( class => 'Fetch::US::Exec::CIA::FOIAReports',
                                      queue => $self->fetch_queue,
                                      data  => { link   => $link->url,
                                                 year   => $year
                                               }
                                    );
            $job->submit;
        }
    }
}

sub _fetch_pdf { 
    my $self = shift;
    my %data = %{ $self->data };

    my $ident = sprintf( 'CIA-FOIA-%04d', $data{year} );
    my $filename = $ident . '.pdf';
    my $key = 'us/exec/cia/' . $filename;

    $self->logger->info( "Storing $data{link} --> $key" );

    my $mech = $self->_mech;
    my $tmpf = File::Temp->new;
    $mech->get( $self->_basedir . $data{link}, ':content_file' => $tmpf->filename );

    $self->store_pdf( key      => $key,
                      datafile => $tmpf,
                      filename => $filename,
                      meta     => { description   => "CIA Freedom of Information Act Annual Report, $data{year}",
                                    identifier    => $ident,
                                  }
                    );

}


1;
